package cn.kgc.vue.aspect;

import cn.hutool.json.JSONUtil;
import cn.kgc.vue.anno.LogAnnotation;
import cn.kgc.vue.entity.LogInfo;
import cn.kgc.vue.service.LogInfoService;
import cn.kgc.vue.utils.IpUtil;
import cn.kgc.vue.utils.JWTUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author: 课工场
 * @since 2023/8/23
 * 日志切面类
 */
@Component
@Aspect
public class LogAspect {

    @Autowired
    private LogInfoService logInfoService;

    @Pointcut("@annotation(cn.kgc.vue.anno.LogAnnotation)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {

        long start = System.currentTimeMillis();
        // 访问目标方法
        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();
        // 耗时
        long time =  end-start;

        // 获取参数 转换成 json字符串
        Object[] args = joinPoint.getArgs();
        String params = JSONUtil.toJsonStr(args);
        //获取方法注解中的相关信息
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        // 操作模块
        String model = annotation.model();
        // 操作描述
        String description = annotation.operation().getDescription();

        // 获取请求对象   ip  请求路径   用户名
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        // 解析token  获取用户名
        String token = request.getHeader("token");
        String username = (String) JWTUtil.getClaim(token).get("username");
        // url
        String uri = request.getRequestURI();
        // 获取ip地址
        String ip = IpUtil.getIp(request);

        // 封装日志参数
        LogInfo logInfo = new LogInfo();
        logInfo.setParams(params);
        logInfo.setUsername(username);
        logInfo.setIp(ip);
        logInfo.setModel(model);
        logInfo.setDescription(description);
        logInfo.setCreateTime(new Date());
        logInfo.setUrl(uri);
        logInfo.setTimeConsuming(time);
        logInfoService.save(logInfo);

        return proceed;
    }


}
